package com.easy.service.impl;

import com.easy.bean.GiveBean;
import com.easy.bean.PostBean;
import com.easy.mapper.GiveDao;
import com.easy.service.GiveService;
import com.easy.service.MessageService;
import com.easy.service.PostService;
import com.easy.util.LogMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GiveServiceImpl implements GiveService {
    @Autowired
    private GiveDao givedao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private PostService postService;
    @Override
    @Transactional
    public int add(GiveBean give) {
        if (give.getUserId() == null || give.getPostId() == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        // 检查是否已经点赞
        if (checkIfLiked(give.getUserId(), give.getPostId())) {
            throw new IllegalArgumentException("已经点赞过了");
        }
        int result = givedao.add(give);
        if (result > 0) {
            // 点赞成功后发送消息（需先获取帖子作者ID）
            PostBean post = postService.get(give.getPostId()); // 需注入PostService
            messageService.sendLikeMessage(
                    post.getUserId(), // 帖子作者ID（接收者）
                    give.getUserId(), // 点赞用户ID（发送者）
                    give.getPostId(),
                    give.getId()
            );
        }

        return result;
    }

    @Override
    public int del(Integer id) {
        return givedao.del(id);
    }

    @Override
    public boolean checkIfLiked(Integer userId, Integer postId) {
        return givedao.checkIfLiked(userId, postId) > 0;
    }

    @Override
    @Transactional
    public int cancelGive(Integer userId, Integer postId) {
        return givedao.cancelGive(userId, postId);
    }

    @Override
    public int getLikeCount(Integer postId) {
        return givedao.getLikeCount(postId);
    }

}